import { CheckAns } from "./CheckAns";

namespace LeetCode0978MaxTurbulenceSize {

    function maxTurbulenceSize(arr: number[]): number {
        if (!arr || arr.length <= 1)
            return arr && arr.length || 0;
        let pos = 1;  // 指针位置
        let maxLen = 1; // 最长符合条件数组长度
        let curLen = 1; // 当前子数组长度
        let lastDelta: number = 0;  // 上一次的差值
        while (pos < arr.length) {
            const delta = arr[pos] - arr[pos - 1];
            if (delta == 0) {
                curLen = 1;
            }
            else if (delta * lastDelta > 0) {
                curLen = 2;
            }
            else {
                curLen++;
                if (curLen > maxLen)
                    maxLen = curLen;
            }
            lastDelta = delta > 0 ? 1 : (delta < 0 ? -1 : 0);
            pos++;
        }
        return maxLen;
    };

    // test
    const testData: { nums: number[], ans: number }[] = [
        { nums: [9, 4, 2, 10, 7, 8, 8, 1, 9], ans: 5 },
        { nums: [4, 8, 12, 16], ans: 2 },
        { nums: [100], ans: 1 }
    ];
    for (const data of testData) {
        const ans = maxTurbulenceSize(data.nums);
        CheckAns(data, ans);
    }
}